package com.wx.spider.common.util;

import org.apache.commons.codec.Charsets;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.Map.Entry;

/**
 * @author:feng
 * @create:2021-04-25 15:58
 */
public class HttpClientUtil {
    public static String getUrlResponse(String url, String charset) {

        CloseableHttpResponse response = null;
        boolean re = false;
        String restr = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpClient httpClient = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(1000).setConnectionRequestTimeout(5000)
                    .setSocketTimeout(1000).build();
            httpGet.setConfig(requestConfig);
            response = (CloseableHttpResponse) httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();

            int L = 1024 * 1024;
            byte buf[] = new byte[L];
            int len = 0;
            byte buf_temp[] = new byte[L];
            int a_i = 0;
            InputStream br = entity.getContent();
            while ((len = br.read(buf_temp)) > 0) {
                if (a_i + len > L) {
                    return null;
                }
                System.arraycopy(buf_temp, 0, buf, a_i, len);
                a_i += len;
            }

            br.close();
            String cs1 = CharactorSetExtractor.extract(new String(buf), "utf-8");
            if (cs1 != null) {
                restr = new String(buf, 0, a_i, cs1);
            }


            httpGet.abort();
            httpGet.releaseConnection();
        } catch (Exception e) {

            return null;

        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return restr;
        }
    }

    //转换为%E4%BD%A0形式
    public static String toUtf8String(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte[] b;
                try {
                    b = String.valueOf(c).getBytes("utf-8");
                } catch (Exception ex) {
//                    System.out.println(ex);
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0)
                        k += 256;
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }

    public static String httpPost(String url, String json) throws Exception {
        // 1、创建一个htt客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(new StringEntity(json, Charsets.UTF_8)); // json格式的字符{"username":"111","password":"111"}
        CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpPost);
        System.out.println(response.getStatusLine().getStatusCode() + "\n");
        HttpEntity entity = response.getEntity();
        String responseContent = EntityUtils.toString(entity, "UTF-8");
        response.close();
        httpClient.close();
        return responseContent;
    }

    public static String postMap(String url, Map<String, String> headerMap, Map<String, String> contentMap) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        List<NameValuePair> content = new ArrayList<NameValuePair>();
        Iterator iterator = contentMap.entrySet().iterator();           //将content生成entity
        while (iterator.hasNext()) {
            Entry<String, String> elem = (Entry<String, String>) iterator.next();
            content.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
        }
        CloseableHttpResponse response = null;
        try {
            Iterator headerIterator = headerMap.entrySet().iterator();          //循环增加header
            while (headerIterator.hasNext()) {
                Entry<String, String> elem = (Entry<String, String>) headerIterator.next();
                post.addHeader(elem.getKey(), elem.getValue());
            }
            if (content.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(content, "UTF-8");
                post.setEntity(entity);
            }
            response = httpClient.execute(post);            //发送请求并接收返回数据
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();       //获取response的body部分
                result = EntityUtils.toString(entity);          //读取reponse的body部分并转化成字符串
            }
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    public static void main(String[] args) {
        HashMap<String, String> headerMap = new HashMap<>();
        headerMap.put("Cookie","wxuin=188794878; devicetype=android-29; lang=zh_CN; rewardsn=; wxtokenkey=777; version=28000335; pass_ticket=VLqW1DAzsmkfLNqHHQMY6Yv3FZaabrs1x6jvBBi1h9cUvtptSml5SKA1j7Y33Q45; appmsg_token=1110_ZDPoHcPptYe7smffG2gragEL-9rWFgwUI9S-cumR57oAzqSQZzCmYQjDGVU~; wap_sid2=CP6Pg1oSigF5X0hMbVBKZ3NmVHM1b3IzMGdkZmpHUjdiZ3R4NWRUZGVjVWhUdFFqVW9PdzRJdXA1N0Npb1EyazZzck8tTVR2Z2N5bzhuQk5zWmd3dVhvckdNOF8yQ2VIajdGSVAtZnFHV1RxdHpCY1NFOUM0YWtxUUJYN1JkenhERUxkRzBSVGNvTXpRU0FBQX4wrOCehAY4DUAB");
        headerMap.put("User-Agent","Mozilla/5.0 (Linux; Android 10; PCT-AL10 Build/HUAWEIPCT-AL10; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/78.0.3904.62 XWEB/2785 MMWEBSDK/20210302 Mobile Safari/537.36 MMWEBID/5825 MicroMessenger/8.0.3.1880(0x28000335) Process/toolsmp WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64");

        String url = "https://mp.weixin.qq.com/mp/getappmsgext";
//        String url = "https://mp.weixin.qq.com/mp/getappmsgext?__biz=MjM5ODEzNDkxNQ==&mid=2650461480&sn=906b0f2f528a0ab2230b99db42182777&idx=1&appmsg_token=1110_ZDPoHcPptYe7smffG2gragEL-9rWFgwUI9S-cumR57oAzqSQZzCmYQjDGVU~&x5=1";

        HashMap<String, String> contentMap = new HashMap<>();
        contentMap.put("is_only_read", "1");
        contentMap.put("is_temp_url", "0");
        contentMap.put("appmsg_type", "9");
        contentMap.put("__biz", "MjM5ODEzNDkxNQ==");
        contentMap.put("mid", "2650461480");
        contentMap.put("sn", "906b0f2f528a0ab2230b99db42182777");
        contentMap.put("idx", "1");
//        contentMap.put("key", "");
//        contentMap.put("pass_ticket", "");
        contentMap.put("appmsg_token", "1110_ZDPoHcPptYe7smffG2gragEL-9rWFgwUI9S-cumR57oAzqSQZzCmYQjDGVU~");

        String res = postMap(url, headerMap, contentMap);
        System.out.println(res);
    }
}

